// app.js
App({
  globalData: {
    userInfo: null,
    isLogin: false,
    userRole: 'user', // user, admin, coach
    baseUrl: 'https://your-api-domain.com/api'
  },

  onLaunch() {
    // 检查登录状态
    this.checkLoginStatus();
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('token');
    if (token) {
      this.globalData.isLogin = true;
      // 获取用户信息
      this.getUserInfo();
    }
  },

  // 获取用户信息
  getUserInfo() {
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.globalData.userInfo = userInfo;
      this.globalData.userRole = userInfo.role || 'user';
    }
  },

  // 登录
  login(userInfo) {
    this.globalData.userInfo = userInfo;
    this.globalData.isLogin = true;
    this.globalData.userRole = userInfo.role || 'user';
    wx.setStorageSync('userInfo', userInfo);
    // 仅当调用方传入了 token 时才写入；否则保留已有 token，避免被默认 mock 覆盖
    if (userInfo && userInfo.token) {
      wx.setStorageSync('token', userInfo.token);
    }
  },

  // 退出登录
  logout() {
    this.globalData.userInfo = null;
    this.globalData.isLogin = false;
    this.globalData.userRole = 'user';
    wx.removeStorageSync('userInfo');
    wx.removeStorageSync('token');
  }
});
